import React, { Component, Fragment } from 'react';
import { Dispatch } from 'redux';
import { connect } from 'dva';

import { Form } from '@ant-design/compatible';
import PageHeader from '@/components/PageHeader';
import { FormComponentProps } from '@ant-design/compatible/es/form';

import { Card } from 'antd';

import { CompanyListItem } from './data';
import BatchIndex from './components/BatchIndex';
import ExpressCard from './components/ExpressCard';

import '@ant-design/compatible/assets/index.css';

interface BatchAddProps extends FormComponentProps {
  dispatch: Dispatch;
  dataInfo: CompanyListItem[];
  INITINFO: any;
}

interface BatchAddState {
  companyID: number;
  type: number;
}

@connect(({
  cooperationCompanyBatch: { dataInfo },
  common: { INITINFO },
}: any) => ({
  dataInfo,
  INITINFO,
}))
class BatchAddElem extends Component<BatchAddProps, BatchAddState> {
  state: BatchAddState = {
    companyID: 4,
    type: 1,
  };

  componentDidMount() {
    this.fetchAction('common/fetchPartner');
    this.fetchAction('common/fetchAddressList');
  }

  componentWillUnmount() {
    this.fetchAction('clear');
  }

  changeCompany = (companyID: number, type: number) => this.setState({ companyID, type });

  handleSubmit = (values: any) => {
    const { companyID: pcId, type } = this.state;
    values = values.map((item: any) => ({
      ...item,
      pcId,
      type,
    }));

    const dataList = JSON.stringify(values);
    const params = { pcId, type, dataList };
    this.fetchAction('operAdd', params);
  };

  fetchAction = (typeName: string, payload: any = {}) => {
    const { dispatch } = this.props;
    const type = typeName.indexOf('common') >= 0
      ? typeName : `cooperationCompanyBatch/${typeName}`;
    dispatch({ type, payload });
  };

  render() {
    const { companyID, type } = this.state;
    const { dataInfo } = this.props;

    const props = {
      dataInfo,
      type,
      companyID,
      submit: this.handleSubmit,
    };

    return (
      <Fragment>
        <PageHeader />

        <BatchIndex changeCompany={this.changeCompany.bind(this)} />

        {dataInfo.length > 0 && (
          <Card bordered={false}>
            <ExpressCard {...props} />
          </Card>
        )}
      </Fragment>
    );
  }
}
export default Form.create<BatchAddProps>()(BatchAddElem);
